package com.zenghus.spring.formework.aop;

/**
 * @author zenghu
 * @date 2018/5/6 14:45
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 默认jdk动态代理
 */
public class AopProxy implements InvocationHandler{

    private Object target;

    private AopConfig config;

    //把原生的对象传过来
    public Object getProxy(Object instance){
        this.target=instance;
        Object proxy=Proxy.newProxyInstance(instance.getClass().getClassLoader(),instance.getClass().getInterfaces(),this);
        return proxy;
    }

    public void setConfig(AopConfig aopConfig){
        this.config=aopConfig;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method m=this.target.getClass().getMethod(method.getName(),method.getParameterTypes());

        if(config.contains(m)){
            AopConfig.Aspect aspect=config.get(m);
            aspect.getPoints()[0].invoke(aspect.getAspect());
        }

        Object obj=method.invoke(this.target,args);

        if(config.contains(m)){
            AopConfig.Aspect aspect=config.get(m);
            aspect.getPoints()[1].invoke(aspect.getAspect());
        }
        return obj;
    }
}
